package cn.edu.uestc.service;

import cn.edu.uestc.pojo.Logistics;
import cn.edu.uestc.pojo.Order;
import cn.edu.uestc.pojo.Product;
import cn.edu.uestc.pojo.User;
import org.apache.juli.logging.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.config.CronTask;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OrderService {
    @Autowired
    HttpServletRequest request;
    @Autowired
    MongoTemplate mongoTemplate;

    public boolean addOrder(Order order) {
        String shopName = order.getShopName();
        String productName = order.getProductName();
        Query query = new Query(Criteria.where("shopName").is(shopName).and("productName").is(productName));
        Product product = mongoTemplate.findOne(query, Product.class, "products");
        if (product.getProductNum() <= 0) {
            return false;
        } else {
            Update update = new Update();
            update.set("productNum", product.getProductNum() - 1);
            mongoTemplate.upsert(query, update, "products");
            mongoTemplate.insert(order, "orders");
            return true;
        }
    }

    public void updateOrder(int id, String address, String operator, boolean isEnd) {
        Query query = new Query(Criteria.where("_id").is(id));
        String status = isEnd ? "待取件" : "运输中";
        Logistics logistics = new Logistics((String) request.getSession().getAttribute("username"), new Date(), address);

        Update update = new Update();
        update.set("status", status);
        update.pop("logistics", Update.Position.LAST);
        mongoTemplate.upsert(query, update, "orders");

        update = new Update();
        update.push("logistics", logistics);
        mongoTemplate.upsert(query, update, "orders");

        if (!isEnd) {
            update = new Update();
            Logistics nextLogistics = new Logistics();
            nextLogistics.setOperator(operator);
            update.push("logistics", nextLogistics);
            mongoTemplate.upsert(query, update, "orders");
        }
    }

    public Order getOrderById(int id) {
        Query query = new Query(Criteria.where("_id").is(id));
        Order order = mongoTemplate.findOne(query, Order.class, "orders");
        return order;
    }

    public boolean deleteOrderById(int id) {
        Query query = new Query(Criteria.where("_id").is(id));
        mongoTemplate.remove(query, Order.class,"orders");
        return  true;
    }

    public List<Order> getAllOrders() {
        List<Order> orderList = new ArrayList<>();
        int userType = (int) request.getSession().getAttribute("user_type");
        if (userType == 0) {
            String username = (String) request.getSession().getAttribute("username");
            Query query = new Query(Criteria.where("username").is(username));
            orderList = mongoTemplate.find(query, Order.class, "orders");
        } else if (userType == 1) {
            String shopName = (String) request.getSession().getAttribute("username");
            Query query = new Query(Criteria.where("shopName").is(shopName));
            orderList = mongoTemplate.find(query, Order.class, "orders");
        } else if (userType == 2) {
            String username = (String) request.getSession().getAttribute("username");
            List<Order> allOrders = mongoTemplate.findAll(Order.class, "orders");
            for (Order order : allOrders) {
                List<Logistics> logisticsList = order.getLogistics();
                Logistics logistics = logisticsList.get(logisticsList.size() - 1);
                if (username.equals(logistics.getOperator()) && !order.getStatus().equals("待取件")) {
                    orderList.add(order);
                }
            }
        }
        return orderList;
    }

    public List<String> getAllShops() {
        List<User> userList = mongoTemplate.findAll(User.class, "users");
        List<String> shopList = new ArrayList<>();
        for (User user : userList) {
            if (user.getType() == 1) {
                shopList.add(user.getUsername());
            }
        }
        return shopList;
    }

    public void acceptOrder(int id, String shipper, String shippingAddress, String shipperPhone, String operator) {
        Query query = new Query(Criteria.where("_id").is(id));
        Order order = new Order();
        order.setShipTime(new Date());
        Logistics logistics = new Logistics();
        logistics.setOperator(operator);
        Update update = new Update();
        update.set("status", "已拣货");
        update.set("shipTime", order.getShipTime());
        update.set("shipper", shipper);
        update.set("shippingAddress", shippingAddress);
        update.set("shipperPhone", Long.parseLong(shipperPhone));
        update.push("logistics", logistics);
        mongoTemplate.upsert(query, update, "orders");
    }

    public void finishOrder(int id) {
        Query query = new Query(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("status", "已签收");
        mongoTemplate.upsert(query, update, "orders");
    }
}
